package cn.wl._04_direct;

import cn.wl.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Rev2 {
    private static final String QUEUE_NAME = "direct_2";

    public static void main(String[] args) throws Exception {
        //获取连接
        Connection connection = ConnectionUtil.getConnection();
        //获取通道
        final Channel channel = connection.createChannel();
        //设置每个消费者只能同时处理一条消息
        channel.basicQos(1);
        //声明一个消息队列
        channel.queueDeclare(
                QUEUE_NAME,
                false,
                false,
                false,
                null);
        //将消息队列绑定到交换机上
        channel.queueBind(QUEUE_NAME, Send.EXCHANGE_NAME_DIRECT,"update");
        channel.queueBind(QUEUE_NAME, Send.EXCHANGE_NAME_DIRECT,"delete");
        //接收消息
        Consumer consumer =new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                //System.out.println(1 / 0);
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("Rev2收到消息："+new String(body));
                //消息处理完后，手动签收消息
                channel.basicAck(
                        deliveryTag,    //要签收消息的id
                        false //是否签收所有消息
                );
            }
        };
        channel.basicConsume(
                QUEUE_NAME, //消息队列的名字，从哪个消息队列拿到消息
                false,                  //true为自动签收：消息队列只要将消息发送给消费者，就会在消息队列中删除
                consumer                        //消费回调方法：处理拿到消息
        );
        //消息收到了，但是是异步执行，主程序结束整个程序就全部结束，回调还来不及处理消息
        //让主程序睡一会，等回调处理完再结束
        Thread.sleep(100000);

    }
}
